/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
limitations under the License.*/

package zuo.biao.library.base;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import org.jetbrains.annotations.Nullable;
import zuo.biao.library.ResourceTable;
import zuo.biao.library.interfaces.ViewPresenter;
import zuo.biao.library.ui.TopTabView;
import zuo.biao.library.util.ResTUtil;
import zuo.biao.library.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**基础带标签的FragmentActivity
 */

public abstract class BaseTabActivity extends BaseAbility implements ViewPresenter
        , Component.ClickedListener, TopTabView.OnTabSelectedListener {
    private static final String TAG = "BaseTabActivity";



    /**
     * @must 1.不要在子类重复这个类中onCreate中的代码;
     *       2.在子类onCreate中super.onCreate(savedInstanceState);
     *       initView();initData();initEvent();
     */

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setContentView(ResourceTable.Layout_base_tab_activity);

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    @Nullable
    private Text tvBaseTabTitle;

    @Nullable
    private Component ivBaseTabReturn;
    @Nullable
    private Text tvBaseTabReturn;
    @Nullable
    private Text tvBaseTabForward;

    @Nullable
    private ComponentContainer llBaseTabTopRightButtonContainer;

    private ComponentContainer llBaseTabTabContainer;
    /**
     * 如果在子类中调用(即super.initView());则view必须含有initView中初始化用到的id(非@Nullable标记)且id对应的View的类型全部相同；
     * 否则必须在子类initView中重写这个类中initView内的代码(所有id替换成可用id)
     */
    @Override
    public void initView() {//必须调用

        tvBaseTabTitle = findView(ResourceTable.Id_tvBaseTabTitle);

        ivBaseTabReturn = findView(ResourceTable.Id_ivBaseTabReturn);
        tvBaseTabReturn = findView(ResourceTable.Id_tvBaseTabReturn);

        llBaseTabTopRightButtonContainer = findView(ResourceTable.Id_llBaseTabTopRightButtonContainer);

        llBaseTabTabContainer = findView(ResourceTable.Id_llBaseTabTabContainer);

    }

    /**
     *  == true >> 每次点击相应tab都加载，调用getFragment方法重新对点击的tab对应的fragment赋值。
     * 如果不希望重载，可以setOnTabSelectedListener，然后在onTabSelected内重写点击tab事件。
     */
    protected boolean needReload = false;
    /**
     * 当前显示的tab所在位置，对应fragment所在位置
     */
    protected int currentPosition = 0;

    /**选择下一个tab和fragment
     */
    public void selectNext() {
        select((getCurrentPosition() + 1) % getCount());
    }
    /**选择tab和fragment
     * @param position 选择位置
     */
    public void select(int position) {
        topTabView.select(position);
    }

    /**选择并显示fragment
     * @param position 位置
     */
    public void selectFragment(int position) {
        if (currentPosition == position) {
            if (needReload) {
                if (fragments[position] != null ) {
                    FractionManager fractionManager = getAbility().getFractionManager();
                    FractionScheduler fractionScheduler = fractionManager.startFractionScheduler();
                    fractionScheduler.remove(fragments[position]);
                    fractionScheduler.submit();
                }
            }else {
                if (fragments[position]!=null){
                    return;
                }
            }
        }

        if (fragments[position]==null){
            fragments[position] = getFragment(position);
        }

        FractionManager fractionManager = getAbility().getFractionManager();
        FractionScheduler fractionScheduler = fractionManager.startFractionScheduler();
        fractionScheduler.hide(fragments[currentPosition]);
        fractionScheduler.add(ResourceTable.Id_flBaseTabFragmentContainer, fragments[position]);
        fractionScheduler.show(fragments[position]);
        fractionScheduler.submit();
        this.currentPosition = position;
    }



    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>










    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    protected TopTabView topTabView;
    private Fraction[] fragments;
    @Override
    public void initData() {//必须调用

        if (tvBaseTabTitle != null) {
            tvBaseTabTitle.setVisibility(StringUtil.isNotEmpty(getTitleName(), true) ? Component.VISIBLE : Component.HIDE);
            tvBaseTabTitle.setText(StringUtil.getTrimedString(getTitleName()));
        }

        //返回按钮<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        String returnName = getReturnName();

        if (returnName == null) {
            if (ivBaseTabReturn != null) {
                ivBaseTabReturn.setVisibility(Component.HIDE);
            }
            if (tvBaseTabReturn != null) {
                tvBaseTabReturn.setVisibility(Component.HIDE);
            }
        } else {
            boolean isReturnButtonHasName = StringUtil.isNotEmpty(returnName, true);
            if (ivBaseTabReturn != null) {
                ivBaseTabReturn.setVisibility(isReturnButtonHasName ? Component.HIDE : Component.VISIBLE);
            }
            if (tvBaseTabReturn != null) {
                tvBaseTabReturn.setVisibility(isReturnButtonHasName ? Component.VISIBLE : Component.HIDE);
                tvBaseTabReturn.setText(StringUtil.getTrimedString(returnName));
            }
        }
        //返回按钮>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        //前进按钮<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        String forwardName = getForwardName();
        if (StringUtil.isNotEmpty(forwardName, true)) {
            tvBaseTabForward = addTopRightButton(newTopRightTextView(context, StringUtil.getTrimedString(forwardName)));
        }

        if (llBaseTabTopRightButtonContainer != null
                && topRightButtonList != null && topRightButtonList.size() > 0) {

            llBaseTabTopRightButtonContainer.removeAllComponents();
            for (Component btn : topRightButtonList) {
                llBaseTabTopRightButtonContainer.addComponent(btn);
            }
        }
        //前进按钮>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


        //tab<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        topTabView = newTopTabView(context, 0, getTopTabViewResId());
        llBaseTabTabContainer.removeAllComponents();
        llBaseTabTabContainer.addComponent(topTabView.createView());
        topTabView.setCurrentPosition(currentPosition);
        topTabView.bindView(getTabNames());
        //tab>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


        //fragmentActivity子界面初始化<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        fragments = new Fraction[getCount()];
        selectFragment(currentPosition);

        //fragmentActivity子界面初始化>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    }

    /**如果需要自定义tab layout 需要实现此方法
     */
    public int getTopTabViewResId() {
        return ResourceTable.Layout_top_tab_view;
    }

    /**TopTabView 构造函数
     * @param context 上下文
     * @param minWidth 最小宽度，传入 0 表示默认值
     * @param layoutId id
     * @return
     */
    public TopTabView newTopTabView(Ability context, int minWidth, int layoutId) {
        return new TopTabView(context, 0, layoutId);
    }


    /**获取导航栏标题名
     * @return null - View.GONE; "" - View.GONE; "xxx" - "xxx"
     */
    @Override
    public String getTitleName() {
        return null;
    }

    /**获取导航栏标题名
     * @return null - View.GONE; "" - <; "xxx" - "xxx"
     */
    @Override
    public String getReturnName() {
        return "";
    }

    //top right button <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**获取导航栏标题名
     * @return null - View.GONE; "" - View.GONE; "xxx" - "xxx"
     */
    @Override
    public String getForwardName() {
        return null;
    }

    @Nullable
    private List<Component> topRightButtonList = new ArrayList<Component>();
    /**添加右上方导航栏按钮
     * @warn 在initData前使用才有效
     * @param topRightButton 不会在这个类设置监听,需要自行设置
     */
    public <V extends Component> V addTopRightButton(V topRightButton) {
        if (topRightButton != null) {
            topRightButtonList.add(topRightButton);
        }
        return topRightButton;
    }
    /**新建右上方导航栏按钮
     * @param context 上下文
     * @param drawable drawable
     * @return Image
     */
    public Image newTopRightImageView(Context context, int drawable) {

    return newTopRightImageView(context, ResTUtil.getPixelMap(context,drawable).get());

    }
    /**新建右上方导航栏按钮
     * @param context 上下文
     * @param drawable drawable
     * @return Image
     */
    public Image newTopRightImageView(Context context, PixelMap drawable) {
        Image topRightButton = (Image) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_top_right_iv, null,true);
        topRightButton.setPixelMap(drawable);
        return topRightButton;
    }
    /**新建右上方导航栏按钮
     * @param context 上下文
     * @param name name
     * @return Text
     */
    public Text newTopRightTextView(Context context, String name) {
        Text topRightButton = (Text) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_top_right_tv, null,true);
        topRightButton.setText(name);
        return topRightButton;
    }

    //top right button >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    /**获取标签名称数组
     * @return getTabNames
     */
    protected abstract String[] getTabNames();

    /**获取新的Fragment
     * @param position 位置
     * @return getFragment
     */
    protected abstract Fraction getFragment(int position);


    /**获取Tab(或Fragment)的数量
     * @return getCount
     */
    public int getCount() {
        return topTabView == null ? 0 : topTabView.getCount();
    }

    /**获取当前Tab(或Fragment)的位置
     * @return getCurrentPosition
     */
    public int getCurrentPosition() {
        return currentPosition;
    }

    public Text getCurrentTab() {
        return topTabView == null ? null : topTabView.getCurrentTab();
    };

    public Fraction getCurrentFragment() {
        return fragments[currentPosition];
    };



    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>










    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initEvent() {//必须调用

        if (ivBaseTabReturn != null) {
            ivBaseTabReturn.setClickedListener(this);
        }
        if (tvBaseTabReturn != null) {
            tvBaseTabReturn.setClickedListener(this);
        }
        if (tvBaseTabForward != null) {
            tvBaseTabForward.setClickedListener(new Component.ClickedListener() {//没有id


                @Override
                public void onClick(Component component) {
                    onForwardClick(component);
                }
            });
        }

        topTabView.setOnTabSelectedListener(this);
    }


    @Override
    public void onTabSelected(Text tvTab, int position, int id) {
        selectFragment(position);
    }

    @Override
    public void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_ivBaseTabReturn ||component.getId() == ResourceTable.Id_tvBaseTabReturn) {
            terminateAbility();
        }
    }


    //生命周期、onActivityResult<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    protected void onStop() {
        super.onStop();
        topTabView = null;
        fragments = null;

        ivBaseTabReturn = null;
        tvBaseTabReturn = null;
        llBaseTabTopRightButtonContainer = null;
        llBaseTabTabContainer = null;

        tvBaseTabTitle = null;

        currentPosition = 0;
        needReload = false;

        topRightButtonList = null;
    }


    //生命周期、onActivityResult>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>








    //内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<



    //内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}